package com.device.api.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;
import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.biz.aep_device_command.CancelCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CancelCommandResponse;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandResponse;
import com.ctg.ag.sdk.biz.aep_device_management.CreateDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.CreateDeviceResponse;
import com.ctg.ag.sdk.biz.aep_device_management.DeleteDeviceRequest;
import com.ctg.ag.sdk.biz.aep_device_management.DeleteDeviceResponse;
import com.device.api.entity.CtwingDeviceResult;
import com.device.api.entity.PudongDeviceConfig;
import com.device.api.mapper.DeviceApiMapper;
import com.device.api.mapper.PudongDeviceConfigMapper;
import com.device.api.r.Result;
import com.device.api.request.DeviceDataSwitchRequest;
import com.device.api.request.DeviceReadDataRequest;

import com.device.api.request.DeviceUploadFrequencyRequest;
import com.device.api.service.ICtWingService;
import com.device.api.service.MqttService;
import com.device.api.utils.MqttClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class ICtWingServiceImpl implements ICtWingService {
    @Autowired
    private AepDeviceManagementClient aepDeviceManagementClient;

    @Autowired
    private AepDeviceCommandClient aepDeviceCommandClient;

    @Autowired
    private PudongDeviceConfigMapper pudongDeviceConfigMapper;
    
    @Autowired
    private DeviceApiMapper deviceApiMapper;

    @Autowired
    private MqttService mqttService;
    @Override
    public void updateDeviceUploadFrequency(DeviceUploadFrequencyRequest deviceUploadFrequencyRequest) {
//        CreateCommandRequest request = new CreateCommandRequest();
        String deviceNo = deviceUploadFrequencyRequest.getDeviceNo();
        PudongDeviceConfig pudongDeviceConfig = pudongDeviceConfigMapper.selectOne(new QueryWrapper<PudongDeviceConfig>().eq("device_no", deviceNo));
        String deviceMasterKey = deviceApiMapper.findDeviceMasterKey(pudongDeviceConfig.getProductId());
        String ctProducId = deviceApiMapper.findDeviceProductId(pudongDeviceConfig.getProductId());

        JSONObject bodyJson = new JSONObject();
        JSONObject payload = new JSONObject();
        JSONObject content = new JSONObject();
        bodyJson.set("deviceId",pudongDeviceConfig.getDeviceCtwingId()); //设备物联网ID
        bodyJson.set("operator","云端");
        bodyJson.set("productId",ctProducId);
        bodyJson.set("level",1);
        String  deviceFrequencyTime ="";
        String unit = deviceUploadFrequencyRequest.getDeviceFrequencyTimeUnit();
        String value = deviceUploadFrequencyRequest.getDeviceFrequencyTime();
        if (unit.equals("ms")){
            deviceFrequencyTime =value;
        }
        if (unit.equals("s")){
            deviceFrequencyTime= String.valueOf(Integer.parseInt(value)*1000);
        }
        if (unit.equals("min")){
            deviceFrequencyTime= String.valueOf(Integer.parseInt(value)*1000*60);
        }
        JSONObject cmd = new JSONObject();
        cmd.set("reportedTime",deviceFrequencyTime);


        payload.set("payload",content); // 服务参数
        content.set("set_reportedTime",cmd);


        bodyJson.set("content",payload);
        mqttService.sendMessage(pudongDeviceConfig,String.valueOf(content));

//        request.setParamMasterKey(deviceMasterKey);
//        System.out.println(bodyJson);
//        request.setBody(String.valueOf(bodyJson).getBytes());
//        try {
//            CreateCommandResponse createCommandResponse = aepDeviceCommandClient.CreateCommand(request);
//            System.out.println(createCommandResponse.toString());
//            String RBody =new String(createCommandResponse.getBody());
//            System.out.println(RBody);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }

    }

    @Override
    public Result<?> deviceAddCtWing(PudongDeviceConfig pudongDeviceConfig) {

        CreateDeviceRequest request = new CreateDeviceRequest();
        String productId = pudongDeviceConfig.getProductId();
        if (productId== null ){
            return Result.error("请输入产品ID");
        }

        if (pudongDeviceConfig.getDeviceNo()== null){
            return Result.error("请输入设备号 or Sn号");
        }

        if (pudongDeviceConfig.getName()== null){
            return Result.error("请输入设备名称");
        }

        String deviceMasterKey = deviceApiMapper.findDeviceMasterKey(productId);
        String ctProducId = deviceApiMapper.findDeviceProductId(productId);

        request.setParamMasterKey(deviceMasterKey);
        request.addParamMasterKey(deviceMasterKey);

        JSONObject body = new JSONObject();
        body.put("productId",ctProducId);
        body.put("deviceSn",pudongDeviceConfig.getDeviceNo());
        body.put("deviceName",pudongDeviceConfig.getName());

        body.put("operator","云端");




        request.setBody(String.valueOf(body).getBytes());
        try {
            CreateDeviceResponse createDeviceResponse = aepDeviceManagementClient.CreateDevice(request);
            String RBody =new String(createDeviceResponse.getBody());
            int statusCode = createDeviceResponse.getStatusCode();
            if (statusCode==200){
                Result result = new Result<>();
                JSONObject jsonObject = new JSONObject(RBody);

                Object code = jsonObject.get("code");

                Object msg = jsonObject.get("msg");

                CtwingDeviceResult r = jsonObject.get("result", CtwingDeviceResult.class);




                if (code.toString().equals("0")){
                    pudongDeviceConfig.setDeviceCtwingId(r.getDeviceId());
                    pudongDeviceConfigMapper.insert(pudongDeviceConfig);
                    result.setCode(200);
                result.setMessage("添加成功");
                result.setResult(r);
                }else {

                    result.setCode(Integer.parseInt(code.toString()));
                    result.setMessage(msg.toString());
                }

             return result;
            }else {
                return Result.error("物联网模块调用失败");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void updateDeviceDataSwitch(DeviceDataSwitchRequest deviceDataSwitchRequest) {
//        CreateCommandRequest request = new CreateCommandRequest();
        String deviceNo = deviceDataSwitchRequest.getDeviceNo();
        PudongDeviceConfig pudongDeviceConfig = pudongDeviceConfigMapper.selectOne(new QueryWrapper<PudongDeviceConfig>().eq("device_no", deviceNo));
//        String deviceMasterKey = deviceApiMapper.findDeviceMasterKey(pudongDeviceConfig.getProductId());
//        String ctProducId = deviceApiMapper.findDeviceProductId(pudongDeviceConfig.getProductId());

        JSONObject bodyJson = new JSONObject();
        JSONObject payload = new JSONObject();
        JSONObject content = new JSONObject();
//        bodyJson.set("deviceId",pudongDeviceConfig.getDeviceCtwingId()); //设备物联网ID
//        bodyJson.set("operator","云端");
//        bodyJson.set("productId",ctProducId);
//        bodyJson.set("level",1);




        JSONObject cmd = new JSONObject();


        content.set("switch",deviceDataSwitchRequest.getDataSwitch());
       // 服务参数
        cmd.set("deviceDataSwitch",content);
        payload.set("payload",cmd);


        bodyJson.set("content",payload);
        mqttService.sendMessage(pudongDeviceConfig,String.valueOf(cmd));
        System.out.println(bodyJson);
//        request.setParamMasterKey(deviceMasterKey);
//        request.setBody(String.valueOf(bodyJson).getBytes());
//        try {
//            CreateCommandResponse createCommandResponse = aepDeviceCommandClient.CreateCommand(request);
//            System.out.println(createCommandResponse.toString());
//            String RBody =new String(createCommandResponse.getBody());
//            System.out.println(RBody);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
    }

    @Override
    public Result<?> deviceDeleteCtWing(String deviceNo) {
//        DeleteDeviceRequest request = new DeleteDeviceRequest();
        Result result = new Result<>();
        PudongDeviceConfig pudongDeviceConfig = pudongDeviceConfigMapper.selectOne(new QueryWrapper<PudongDeviceConfig>().eq("device_no", deviceNo));
        if (pudongDeviceConfig == null) {
            result.setCode(4004);
            result.setMessage("此设备不存在:" + deviceNo);
            return result;
        }
//        String deviceMasterKey = deviceApiMapper.findDeviceMasterKey(pudongDeviceConfig.getProductId());
//        String ctProducId = deviceApiMapper.findDeviceProductId(pudongDeviceConfig.getProductId());
//
//        request.setParamMasterKey(deviceMasterKey);
//        request.setParamProductId(ctProducId);
//        request.setParamDeviceIds(pudongDeviceConfig.getDeviceCtwingId());
//        try {
//            DeleteDeviceResponse deleteDeviceResponse = aepDeviceManagementClient.DeleteDevice(request);
//
//            String RBody = new String(deleteDeviceResponse.getBody());
//            System.out.println(RBody);
//            JSONObject jsonObject = new JSONObject(RBody);
//
//            Object code = jsonObject.get("code");
//
//
//            if (code.toString().equals("0")) {
                QueryWrapper<PudongDeviceConfig> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("device_no", deviceNo);
                int delete = this.pudongDeviceConfigMapper.delete(queryWrapper);
//                result.setCode(200);
//                result.setMessage("删除成功");
//
//                return result;
//            }
//            if (code.toString().equals("1127")) {
//                QueryWrapper<PudongDeviceConfig> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("device_no", deviceNo);
//                int delete = this.pudongDeviceConfigMapper.delete(queryWrapper);
//
//                if (delete == 0) {
//                    result.setCode((Integer) code);
//                    result.setMessage("此设备不存在:" + deviceNo);
//                    return result;
//                } else {
//                    result.setCode(200);
//                    result.setMessage("删除成功");
//                    return result;
//                }
//
//            }
            result.setCode(200);
            result.setMessage("删除成功");
            return result;

//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
    }

    @Override
    public Result<?> setTimeCalibration(Object deviceNo) {
        Result result = new Result<>();
//        CreateCommandRequest request = new CreateCommandRequest();

        PudongDeviceConfig pudongDeviceConfig = pudongDeviceConfigMapper.selectOne(new QueryWrapper<PudongDeviceConfig>().eq("device_no", deviceNo));
//        String deviceMasterKey = deviceApiMapper.findDeviceMasterKey(pudongDeviceConfig.getProductId());
//        String ctProducId = deviceApiMapper.findDeviceProductId(pudongDeviceConfig.getProductId());

        JSONObject bodyJson = new JSONObject();
        JSONObject payload = new JSONObject();
        JSONObject content = new JSONObject();
//        bodyJson.set("deviceId",pudongDeviceConfig.getDeviceCtwingId()); //设备物联网ID
//        bodyJson.set("operator","云端");
////        bodyJson.set("productId",ctProducId);
//        bodyJson.set("level",1);




        JSONObject cmd = new JSONObject();
        // 定义日期格式化对象
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 取当前时间
        Date date = new Date();
        // 格式化当前时间
        String nowTime = simpleDateFormat.format(date);

        content.set("datetime",nowTime);
        // 服务参数
        cmd.set("set_datetime",content);
        payload.set("payload",cmd);


        bodyJson.set("content",payload);

        mqttService.sendMessage(pudongDeviceConfig,String.valueOf(cmd));


//        mqttService.sendMqttMessage("device_control",String.valueOf(cmd));
//        System.out.println(bodyJson);
//        request.setParamMasterKey(deviceMasterKey);
//        request.setBody(String.valueOf(bodyJson).getBytes());
//        try {
//            CreateCommandResponse createCommandResponse = aepDeviceCommandClient.CreateCommand(request);
//            System.out.println(createCommandResponse.toString());
//            String RBody =new String(createCommandResponse.getBody());
//            JSONObject jsonObject = new JSONObject(RBody);
//
//            Object code = jsonObject.get("code");
//            if (code.toString().equals("0")) {
//
//                result.setCode(200);
//                result.setMessage("指令已保存");
//
//                return result;
//            }else {
//                result.setCode(500);
//                result.setMessage("发送失败");
//
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        result.setCode(200);
        result.setMessage("指令已保存");
        return result;
    }

    @Override
    public Result<?> getDeviceTime(Object deviceNo) {
        Result result = new Result<>();
        CreateCommandRequest request = new CreateCommandRequest();

        PudongDeviceConfig pudongDeviceConfig = pudongDeviceConfigMapper.selectOne(new QueryWrapper<PudongDeviceConfig>().eq("device_no", deviceNo));
//        String deviceMasterKey = deviceApiMapper.findDeviceMasterKey(pudongDeviceConfig.getProductId());
//        String ctProducId = deviceApiMapper.findDeviceProductId(pudongDeviceConfig.getProductId());

        JSONObject bodyJson = new JSONObject();
        JSONObject payload = new JSONObject();
        JSONObject content = new JSONObject();
//        bodyJson.set("deviceId",pudongDeviceConfig.getDeviceCtwingId()); //设备物联网ID
//        bodyJson.set("operator","云端");
//        bodyJson.set("productId",ctProducId);
//        bodyJson.set("level",1);




        JSONObject cmd = new JSONObject();

        // 服务参数
        cmd.set("gettime","0");
        payload.set("payload",cmd);


        bodyJson.set("content",payload);

        mqttService.sendMessage(pudongDeviceConfig,String.valueOf(cmd));
//        System.out.println(bodyJson);
//        request.setParamMasterKey(deviceMasterKey);
//        request.setBody(String.valueOf(bodyJson).getBytes());
//        try {
//            CreateCommandResponse createCommandResponse = aepDeviceCommandClient.CreateCommand(request);
//            System.out.println(createCommandResponse.toString());
//            String RBody =new String(createCommandResponse.getBody());
//            JSONObject jsonObject = new JSONObject(RBody);
//
//            Object code = jsonObject.get("code");
//            if (code.toString().equals("0")) {
//
//                result.setCode(200);
//                result.setMessage("指令已保存");
//
//                return result;
//            }else {
//                result.setCode(500);
//                result.setMessage("发送失败");
//
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        result.setCode(200);
        result.setMessage("指令已保存");
        return result;
    }

    @Override
    public Result<?> deviceReadData(DeviceReadDataRequest request2) {
        Result result = new Result<>();
        CreateCommandRequest request = new CreateCommandRequest();

        PudongDeviceConfig pudongDeviceConfig = pudongDeviceConfigMapper.selectOne(new QueryWrapper<PudongDeviceConfig>().eq("device_no", request2.getDeviceNo()));
//        String deviceMasterKey = deviceApiMapper.findDeviceMasterKey(pudongDeviceConfig.getProductId());
//        String ctProducId = deviceApiMapper.findDeviceProductId(pudongDeviceConfig.getProductId());

        JSONObject bodyJson = new JSONObject();
        JSONObject payload = new JSONObject();
        JSONObject content = new JSONObject();
//        bodyJson.set("deviceId",pudongDeviceConfig.getDeviceCtwingId()); //设备物联网ID
//        bodyJson.set("operator","云端");
//        bodyJson.set("productId",ctProducId);
//        bodyJson.set("level",1);




        JSONObject cmd = new JSONObject();

        // 定义日期格式化对象
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(request2.getDatetime());


        content.set("datetime",format);
        // 服务参数
        cmd.set("read_data",content);
        payload.set("payload",cmd);


        bodyJson.set("content",payload);
        mqttService.sendMessage(pudongDeviceConfig,String.valueOf(cmd));
//        System.out.println(bodyJson);
//        request.setParamMasterKey(deviceMasterKey);
//        request.setBody(String.valueOf(bodyJson).getBytes());
//        try {
//            CreateCommandResponse createCommandResponse = aepDeviceCommandClient.CreateCommand(request);
//            System.out.println(createCommandResponse.toString());
//            String RBody =new String(createCommandResponse.getBody());
//            JSONObject jsonObject = new JSONObject(RBody);
//
//            Object code = jsonObject.get("code");
//            if (code.toString().equals("0")) {
//
//                result.setCode(200);
//                result.setMessage("指令已保存");
//
//                return result;
//            }else {
//                result.setCode(500);
//                result.setMessage("发送失败");
//
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
        result.setCode(200);
        result.setMessage("指令已保存");
        return result;
    }

    @Override
    public Result<?> setDeviceIp(Object deviceNo, Object ip) {
        Result result = new Result<>();
        JSONObject content = new JSONObject();
        JSONObject cmd = new JSONObject();
        content.set("ip",ip);
        // 服务参数
        cmd.set("set_ip",content);

        if (deviceNo.equals("ALL")){
            List<PudongDeviceConfig> pudongDeviceConfigs = pudongDeviceConfigMapper.selectList(new QueryWrapper<PudongDeviceConfig>());
            for (PudongDeviceConfig deviceConfig : pudongDeviceConfigs) {
                mqttService.sendMessage(deviceConfig,String.valueOf(cmd));
            }

        }else {
            PudongDeviceConfig pudongDeviceConfig = pudongDeviceConfigMapper.selectList(new QueryWrapper<PudongDeviceConfig>().eq("device_no", deviceNo)).get(0);
            mqttService.sendMessage(pudongDeviceConfig,String.valueOf(cmd));

        }
        result.setCode(200);
        result.setMessage("指令已保存");
        return result;
    }
}
